[Vue] useStore 是甚麼概念? 如何運作?


Posted by Engine Lai on 2023-11-12

useStore 是 Vuex 4(Vue.js 3 的狀態管理庫)中的一個新函數,它是組合式 API 的一部分。這個函數用於在支持組合式 API 的 Vue.js 組件中訪問 Vuex store 的實例。useStore 提供了一種在 setup 函數中獲取 store 的引用的方式,而不需要依賴 this 上下文,這在 Vue.js 3 的組合式 API 中是不可用的。

以下是 useStore 如何在 Vue.js 組件中運作的基本步驟:

  1. 導入 useStore 函數
    首先,你需要從 vuex 包中導入 useStore 函數。

    import { useStore } from 'vuex';
    
  2. 在組件的 setup 函數中調用 useStore
    setup 函數中調用 useStore 可以獲取到 store 的實例。

    setup() {
      const store = useStore();
      // 現在你可以使用 store 中的 state、getters、mutations 和 actions
      return {
        //...
      };
    }
    
  3. 訪問 Vuex 狀態、提交 mutations 或派發 actions
    一旦獲取了 store 的實例,你就可以在 setup 函數中或其他由 setup 函數返回的函數中訪問 Vuex 的狀態(state)、執行 mutations 和 actions。

    setup() {
      const store = useStore();
      const count = computed(() => store.state.count);
    
      function increment() {
        store.commit('increment');
      }
    
      function asyncIncrement() {
        store.dispatch('asyncIncrement');
      }
    
      return {
        count,
        increment,
        asyncIncrement,
      };
    }
    

在 Vuex 中,store 是全局的,意味著它在整個應用中是單一的。這允許組件共享狀態,並保持狀態的一致性。使用 useStore 函數是在 Vue.js 3 中使用組合式 API 時訪問 Vuex store 的標準方式。這種方法將 Vuex 的集中式狀態管理與 Vue.js 3 的組合式 API 相結合,使得代碼更加模組化和可測試。


#Vue







Related Posts

橢圓軌道上行星到太陽平均距離

橢圓軌道上行星到太陽平均距離

ASP.NET Core Web API 入門教學 - 關鍵字搜尋

ASP.NET Core Web API 入門教學 - 關鍵字搜尋

jQuery 常用語法

jQuery 常用語法


Comments